package com.gitee.loyo.jdbc

import java.math.BigDecimal
import java.sql.ResultSet
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.util.*

fun interface ResultSetHandler<T> {

    fun handle(rs: ResultSet, i: Int): T

    companion object {
        var SHORT: ResultSetHandler<Short?> = ResultSetHandler { rs: ResultSet, i: Int -> rs.getShort(i) }
        var INT: ResultSetHandler<Int?> =  ResultSetHandler { rs: ResultSet, i: Int -> rs.getInt(i) }
        var LONG: ResultSetHandler<Long?> = ResultSetHandler { rs: ResultSet, i: Int -> rs.getLong(i) }
        var FLOAT: ResultSetHandler<Float?> = ResultSetHandler { rs: ResultSet, i: Int -> rs.getFloat(i) }
        var DOUBLE: ResultSetHandler<Double?> = ResultSetHandler { rs: ResultSet, i: Int -> rs.getDouble(i) }
        var BOOLEAN: ResultSetHandler<Boolean?> = ResultSetHandler { rs: ResultSet, i: Int -> rs.getBoolean(i) }
        var STRING: ResultSetHandler<String?> = ResultSetHandler { rs: ResultSet, i: Int -> rs.getString(i) }
        var DATE: ResultSetHandler<Date?> = ResultSetHandler { rs: ResultSet, i: Int -> rs.getTimestamp(i)?.let { o -> Date.from(o.toInstant()) } }
        var LOCAL_DATE: ResultSetHandler<LocalDate?> = ResultSetHandler { rs: ResultSet, i: Int -> rs.getDate(i)?.toLocalDate()  }
        var LOCAL_TIME: ResultSetHandler<LocalTime?> = ResultSetHandler { rs: ResultSet, i: Int -> rs.getTime(i)?.toLocalTime() }
        var LOCAL_DATE_TIME: ResultSetHandler<LocalDateTime?> = ResultSetHandler { rs: ResultSet, i: Int -> rs.getTimestamp(i)?.toLocalDateTime()  }
        var BIG_DECIMAL: ResultSetHandler<BigDecimal?> = ResultSetHandler { rs: ResultSet, i: Int -> rs.getBigDecimal(i) }
        var BYTE_ARRAY: ResultSetHandler<ByteArray?> = ResultSetHandler { rs: ResultSet, i: Int -> rs.getBytes(i) }
        var INT_ARRAY: ResultSetHandler<Array<Int>?> = ResultSetHandler { rs: ResultSet, i: Int -> rs.getArray(i)?.array as Array<Int> }
        var STRING_ARRAY: ResultSetHandler<Array<String>?> = ResultSetHandler { rs: ResultSet, i: Int -> rs.getArray(i)?.array as Array<String> }
        var BIG_DECIMAL_ARRAY: ResultSetHandler<Array<BigDecimal>?> = ResultSetHandler { rs: ResultSet, i: Int -> rs.getArray(i)?.array as Array<BigDecimal> }
        var OBJECT_ARRAY: ResultSetHandler<Array<Any>?> = ResultSetHandler { rs: ResultSet, i: Int -> rs.getArray(i)?.array as Array<Any> }
    }
}